const { baseUrl } = require("../../config")
Component({
  properties: {
    agencyId: {
      type: String
    }
  },
  data: {
    left: [],
    right: [],
    unknowfield: 0
  },
  lifetimes: {
    attached() {
      this.fetchList()
    }
  },
  methods: {
    fetchList() {
      const token = wx.getStorageSync("token")
      // 可测试机构id: 1003, 404
      const url = baseUrl + "/api/home/visitor-notes?agencyId=" + this.properties.agencyId
      wx.request({
        url,
        method: "POST",
        header: {
          "X-Requested-With": "XMLHttpRequest",
          Authorization: token ? "Bearer " + JSON.parse(token) : ""
        },
        data: {
          pagination: {
            pageSize: 6,
            current: 1
          },
          sort: {
            predicate: "updatedTime",
            reverse: true
          },
          search: {}
        },
        dataType: "json",
        success: res => {
          console.log("req success: ", { url, method: "POST" }, res.data)
          const { data, success } = res.data
          if (success && data) {
            for (let i = 0; i < data.list.length; i++) {
              const item = data.list[i]
              item.title = this.getShowTitle(item)
              item.createdByHead = item.createdByHead || "/images/yikao-community/defAvatar.png"
              if (i % 2 === 0) {
                this.data.left.push(item)
              } else {
                this.data.right.push(item)
              }
            }
            this.setData({
              left: this.data.left,
              right: this.data.right,
              unknowfield: data.extendData.miniVisitorId
            })
          }
        }
      })
    },
    getShowTitle(noteItem) {
      if (noteItem.title) return noteItem.title
      if (noteItem.description) {
        return noteItem.description.split(/\r?\n+/).join("")
      }
      return ""
    },
    handleLike(ev) {
      const { id, field } = ev.currentTarget.dataset
      const token = wx.getStorageSync("token")
      wx.request({
        url: baseUrl + "/api/my/like-note/" + id,
        method: "POST",
        header: {
          "X-Requested-With": "XMLHttpRequest",
          Authorization: token ? "Bearer " + JSON.parse(token) : ""
        },
        dataType: "json",
        success: res => {
          const { data, success } = res.data
          if (success && data) {
            const { isLike, likeCount } = data
            wx.showToast({
              title: !isLike ? "已取消点赞" : "点赞成功",
              icon: "none"
            })
            const index = this.data[field].findIndex(l => l.id === id)
            const patchKey1 = `${field}[${index}].isSelfLike`
            const patchKey2 = `${field}[${index}].likeCount`
            this.setData({
              [patchKey1]: isLike,
              [patchKey2]: likeCount
            })
          }
        }
      })
    }
  }
})
